<template>
  <div>
    <!-- 筛选器 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="22">
          <el-radio-group v-model="filterCondition" @change="handleFilterChange">
            <el-radio label="all">全部商品</el-radio>
            <el-radio label="hot">热销推荐</el-radio>
            <el-radio label="new">新品推荐</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" icon="el-icon-plus" @click="add_book">添加书籍</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格显示区 -->
    <el-card class="table-card">
      <el-table :data="currentTableData" border style="width: 100%">
        <el-table-column prop="b_id" label="书籍ID" width="180"></el-table-column>
        <el-table-column prop="b_isbn" label="Isbn名称" width="180"></el-table-column>
        <el-table-column prop="b_name" label="书籍名称" width="180"></el-table-column>
        <el-table-column prop="b_author" label="书籍作者" width="180"></el-table-column>
        <el-table-column prop="b_publisher" label="出版社" width="180"></el-table-column>
        <el-table-column prop="b_cover" label="书籍封面" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.b_cover" style="width: 80px;height: 110px;">
          </template>
        </el-table-column>
        <el-table-column prop="b_image1" label="书籍图片1" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.b_image1" style="width: 80px;height: 110px;">
          </template>
        </el-table-column>
        <el-table-column prop="b_image2" label="书籍图片2" width="120">
          <template slot-scope="scope">
            <img :src="scope.row.b_image2" style="width: 80px;height: 110px;">
          </template>
        </el-table-column>
        <el-table-column prop="b_price" label="书籍价格"></el-table-column>
        <el-table-column prop="bt_id" label="书籍类别" width="180"></el-table-column>
        <el-table-column prop="b_stock" label="书籍库存" width="180"></el-table-column>
        <el-table-column prop="b_mark" label="书籍介绍" width="180">
          <template slot-scope="scope">
            <el-tooltip effect="dark" :content="scope.row.b_mark" placement="top">
              <span>{{ scope.row.b_mark.slice(0, 50) }}...</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="b_time" label="上架时间" width="180" :formatter="dataformatter"></el-table-column>

        <!-- 表格的操作栏 -->
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-button @click="handleRemoveHot(scope.row)" type="warning" size="small">加入热销</el-button>
              </el-col>
              <el-col :span="12">
                <el-button @click="handleAddNewProduct(scope.row)" type="success" size="small">加入新品</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="10" style="margin-top: 10px;">
              <el-col :span="10">
                <el-button @click="update_book(scope.row)" type="info" size="small">修改</el-button>
              </el-col>
              <el-col :span="12">
                <el-button @click="delete_book(scope.row)" type="danger" size="small">删除</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredTableData.length">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog
        @close="closeDialog"
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-form :model="book_form" :rules="rules" ref="book_form">
        <el-form-item label="Isbn名称" :label-width="formLabelWidth" prop="b_isbn">
          <el-input v-model="book_form.b_isbn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍名称" :label-width="formLabelWidth" prop="b_name">
          <el-input v-model="book_form.b_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍作者" :label-width="formLabelWidth" prop="b_author">
          <el-input v-model="book_form.b_author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍出版社" :label-width="formLabelWidth" prop="b_publisher">
          <el-input v-model="book_form.b_publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍封面" :label-width="formLabelWidth" prop="b_cover">
          <!-- 上传控件-->
          <el-upload
              ref="uploadCover"
              class="avatar-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="change_icon"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="书籍图片1" :label-width="formLabelWidth" prop="b_image1">
          <!-- 上传控件-->
          <el-upload
              ref="uploadImage1"
              class="avatar-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="change_icon1"
              :before-upload="beforeAvatarUpload1">
            <img v-if="imageUrl1" :src="imageUrl1" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="书籍图片2" :label-width="formLabelWidth" prop="b_image2">
          <!-- 上传控件-->
          <el-upload
              ref="uploadImage2"
              class="avatar-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="change_icon2"
              :before-upload="beforeAvatarUpload2">
            <img v-if="imageUrl2" :src="imageUrl2" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="书籍价格" :label-width="formLabelWidth" prop="b_price">
          <el-input v-model="book_form.b_price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍类别" :label-width="formLabelWidth" prop="bt_id">
          <el-input v-model="book_form.bt_id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍库存" :label-width="formLabelWidth" prop="b_stock">
          <el-input v-model="book_form.b_stock" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍介绍" :label-width="formLabelWidth" prop="b_mark">
          <el-input type="textarea" v-model="book_form.b_mark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上架时间" :label-width="formLabelWidth" prop="b_time">
          <el-date-picker
              v-model="book_form.b_time"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getBookList();
  },
  data() {
    return {
      book_form: {
        b_id: '',
        b_isbn: '',
        b_name: '',
        b_author: '',
        b_publisher: '',
        b_cover: '',
        b_image1: '',
        b_image2: '',
        b_price: '',
        bt_id: '',
        b_stock: '',
        b_mark: '',
        b_time: '',
      },
      rules: {
        b_name: [
          { required: true, message: '请输入书名', trigger: 'blur' },
        ],
      },
      isdisable: false, // 账号框是否禁用
      dialogVisible: false,
      dialogTitle: "",
      formData: new FormData(), // 表单类型的数据对象，可以包含文件
      imageUrl: '', // 上传头像的地址
      imageUrl1: '', // 上传头像的地址
      imageUrl2: '', // 上传头像的地址
      formLabelWidth: '120px',
      tableData: [],
      filterCondition: 'all', // 当前筛选条件
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
    };
  },
  computed: {
    filteredTableData() {
      if (this.filterCondition === 'all') {
        return this.tableData;
      } else {
        return this.tableData.filter(item => item.recommendationType === this.filterCondition);
      }
    },
    currentTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTableData.slice(start, end);
    }
  },
  methods: {
    // 获取书籍数据
    async getBookList() {
      const { data: res } = await this.$axios.get("/book/listBook");
      console.log(res);
      this.tableData = res.data;
    },
    handleRemoveHot(val) {
      console.log('移除热销操作', val);
      // 在这里添加移除热销的处理逻辑
    },
    handleAddNewProduct(val) {
      console.log('加入新品操作', val);
      // 在这里添加加入新品的处理逻辑
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleFilterChange() {
      this.currentPage = 1; // 重置到第一页
    },
    // 关闭对话框
    closeDialog() {
      this.$refs.book_form.resetFields(); // 重置表单
      this.imageUrl = ''; // 清空表单
      this.imageUrl1 = ''; // 清空表单
      this.imageUrl2 = ''; // 清空表单
      this.formData = new FormData(); // 重置formData对象的数据
      this.book_form = { // 重置book_form对象
        b_id: '',
        b_isbn: '',
        b_name: '',
        b_author: '',
        b_publisher: '',
        b_cover: '',
        b_image1: '',
        b_image2: '',
        b_price: '',
        bt_id: '',
        b_stock: '',
        b_mark: '',
        b_time: '',
      };
      this.getBookList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    // 头像上传成功
    change_icon(file) {
      // 图片预览图访问地址
      this.imageUrl = URL.createObjectURL(file.raw);
      this.formData.delete("file");
      if (this.imageUrl) {
        this.formData.append("files", file.raw);
        console.log(this.formData);
      }
    },
    change_icon1(file) {
      // 图片预览图访问地址
      this.imageUrl1 = URL.createObjectURL(file.raw);
      this.formData.delete("file");
      if (this.imageUrl1) {
        this.formData.append("files", file.raw);
        console.log(this.formData);
      }
    },
    change_icon2(file) {
      // 图片预览图访问地址
      this.imageUrl2 = URL.createObjectURL(file.raw);
      this.formData.delete("file");
      if (this.imageUrl2) {
        this.formData.append("files", file.raw);
        console.log(this.formData);
      }
    },
    // 头像上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 10;
      console.log(file.type);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload1(file) {
      const isJPG = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 10;
      console.log(file.type);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    beforeAvatarUpload2(file) {
      const isJPG = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 10;
      console.log(file.type);
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    // 提交表单
    subForm() {
      this.$refs.book_form.validate(async (valid) => {
        if (valid) {
          // 把book_form中的数据封装到formData
          if (this.book_form.b_time) {
            this.book_form.b_time = new Date(this.book_form.b_time);
          } else {
            this.book_form.b_time = new Date();
          }
          for (let key in this.book_form) {
              this.formData.append(key, this.book_form[key]);
          }
          console.log(this.formData);
          // 请求后端添加用户接口
          const { data: res } = await this.$axios.post("/book/addOrUpdate", this.formData);
          console.log(res);
          if (res.data) {
            this.$message.success("操作成功");
            this.dialogVisible = false;
            await this.getBookList();
          } else {
            this.$message.error("添加失败");
            return false;
          }
        }
      });
    },
    dataformatter(row) {
      if (row.b_time) {
        let date = new Date(row.b_time);
        return date.toLocaleString();
      }
    },
    // 添加用户
    add_book() {
      this.dialogVisible = true;
      this.dialogTitle = "添加书籍";
      this.isdisable = false;
    },
    // 修改书籍
    update_book(row) {
      console.log(this.formData);
      this.book_form = row;
      this.imageUrl = row.b_cover;
      this.imageUrl1 = row.b_image1;
      this.imageUrl2 = row.b_image2;
      this.dialogVisible = true;
      this.dialogTitle = "修改书籍信息";
      this.isdisable = true;
    },
    // 删除书籍
    delete_book(row) {
      this.$confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.get("/book/deleteBookById", { params: { b_id: row.b_id } });
        if (res.data) {
          this.$message.success('删除成功');
          await this.getBookList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  }
};
</script>

<style scoped>
.filter-card {
  margin-top: 10px; /* 调整这个值以减少卡片之间的间距 */
  padding: 20px;
}

.table-card {
  margin-top: 10px; /* 调整这个值以减少卡片之间的间距 */
  padding: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

